package com.codejoys.ssm.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 认证失败的统一处理入口
@Component
public class TmsAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static final Logger logger = LoggerFactory.getLogger(TmsAuthenticationEntryPoint.class);

    // 未登录时，会调用这个方法处理请求
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        logger.warn("未登录", authException);

        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());

        // 不要跳转到登录界面，去掉spring security的默认行为
        // response.sendRedirect("/login");
    }
}
